import type { AxiosResponse } from 'axios';
import type { RequestOptions, Result } from '/#/axios';
import type { AxiosTransform, CreateAxiosOptions } from './axiosTransform';
import { VAxios } from './Axios';
import { useGlobSetting } from '/@/hooks/setting';
import type { GlobConfig } from '/#/config';
import { isString } from '/@/utils/is';
import { deepMerge, setObjToUrlParams } from '/@/utils';
import { t } from '/@/hooks/web/useI18n';
import { formatRequestDate, joinTimestamp, slRspFormatter } from './helper';
import { useMessage } from '/@/hooks/web/useMessage';
import { ContentTypeEnum, RequestEnum } from '/@/enums/httpEnum';
import { checkStatus } from './checkStatus';
import { useUserStoreWithout } from '/@/store/modules/user';

const { createMessage, createErrorModal } = useMessage();
const globSetting: GlobConfig = useGlobSetting();
const urlPrefix = globSetting.urlPrefix;

const transform: AxiosTransform = {
  /**
   * @description: 处理请求数据。如果数据不是预期格式，可直接抛出错误
   */
  transformRequestHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
    const { isTransformResponse, isReturnNativeResponse } = options;
    const response = res.data;
    // 是否返回原生响应头 比如：需要获取响应头时使用该属性
    switch (true) {
      case isReturnNativeResponse: {
        return res;
      }
      case !isTransformResponse: {
        return res.data;
      }
      // 不进行任何处理，直接返回
      // 用于页面代码可能需要直接获取code，data，message这些信息时开启
      case !(response as unknown): {
        throw new Error(t('sys.api.apiRequestFailed'));
      }
    }
    // SaaS Landing 项目接口返回格式
    return slRspFormatter(response, options);
  },

  // 请求之前处理config
  beforeRequestHook: (config, options) => {
    const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true, urlPrefix } = options;

    if (joinPrefix) {
      config.url = `${urlPrefix}${config.url}`;
    }

    if (apiUrl && isString(apiUrl)) {
      config.url = `${apiUrl}${config.url}`;
    }
    const params = config.params || {};
    const data = config.data || false;
    formatDate && data && !isString(data) && formatRequestDate(data);
    if (config.method?.toUpperCase() === RequestEnum.GET) {
      if (!isString(params)) {
        // 给 get 请求加上时间戳参数，避免从缓存中拿数据。
        config.params = Object.assign(params || {}, joinTimestamp(joinTime, false));
      } else {
        // 兼容restful风格
        config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
        config.params = undefined;
      }
    } else {
      if (!isString(params)) {
        formatDate && formatRequestDate(params);
        if (Reflect.has(config, 'data') && config.data && Object.keys(config.data).length > 0) {
          config.data = data;
          config.params = params;
        } else {
          // 非GET请求如果没有提供data，则将params视为data
          config.data = params;
          config.params = undefined;
        }
        if (joinParamsToUrl) {
          config.url = setObjToUrlParams(config.url as string, {
            ...config.params,
            ...config.data,
          });
        }
      } else {
        // 兼容restful风格
        config.url = config.url + params;
        config.params = undefined;
      }
    }
    return config;
  },

  /**
   * @description: 请求拦截器处理
   */
  requestInterceptors: (config, options) => {
    // 请求之前处理config
    const userStore = useUserStoreWithout();
    const token = userStore.getToken;

    if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
      (config as Recordable).headers.Authorization = options.authenticationScheme
        ? `${options.authenticationScheme} ${token}`
        : token;
    }
    (config as Recordable).headers['tenantCode'] = userStore.getUserInfo?.tenantCode || '';
    (config as Recordable).headers['token'] = token || '';
    return config;
  },

  /**
   * @description: 响应拦截器处理
   */
  responseInterceptors: (res: AxiosResponse<unknown>) => {
    return res;
  },

  /**
   * @description: 响应错误处理
   */
  responseInterceptorsCatch: (error: any) => {
    const { code, message, config, response } = error || {};
    const errorMessageMode = config?.requestOptions?.errorMessageMode || 'none';
    const err: string = error?.toString?.() ?? '';
    const msg: string = response?.data?.error?.message ?? '';
    let errMessage = '';

    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        errMessage = '接口超时';
      }
      if (err?.includes('Network Error')) {
        errMessage = '网络问题';
      }

      if (errMessage) {
        if (errorMessageMode === 'modal') {
          createErrorModal({
            title: '请求错误',
            content: errMessage,
          });
        } else if (errorMessageMode === 'message') {
          createMessage.error(errMessage);
        }
        return Promise.reject(error);
      }
    } catch (error) {
      throw new Error(error as unknown as string);
    }
    checkStatus(error?.response?.status, msg, errorMessageMode);
    return Promise.reject(error);
  },
};

function createAxios(opt?: Partial<CreateAxiosOptions>) {
  return new VAxios(
    deepMerge(
      {
        // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#authentication_schemes
        // authentication schemes，e.g: Bearer
        // authenticationScheme: 'Bearer',
        authenticationScheme: '',
        timeout: 10 * 1000,
        // 基础接口地址

        // baseURL: '127.0.0.1',
        headers: { 'Content-Type': ContentTypeEnum.JSON },
        // 如果是form-data格式
        // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
        // 数据处理方式
        transform,
        // 配置项，下面的选项都可以在独立的接口请求中覆盖
        requestOptions: {
          // 默认将prefix 添加到url
          joinPrefix: true,
          // 是否返回原生响应头 比如：需要获取响应头时使用该属性
          isReturnNativeResponse: false,
          // 需要对返回数据进行处理
          isTransformResponse: true,
          // post请求的时候添加参数到url
          joinParamsToUrl: false,
          // 格式化提交参数时间
          formatDate: true,
          // 消息提示类型
          errorMessageMode: 'message',
          // 接口地址
          apiUrl: globSetting.apiUrl,
          // 接口拼接地址
          urlPrefix: urlPrefix,
          //  是否加入时间戳
          joinTime: true,
          // 忽略重复请求
          ignoreCancelToken: true,
          // TODO: 修改为false
          // 是否携带token
          withToken: false,
        },
      },
      opt || {}
    )
  );
}

export const defHttp = createAxios();

// 租户微服务Axios对象
export const tenantHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslandingTenant',
  },
});

// 授权微服务Axios对象
export const authorityHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-authority',
  },
});

export const authorityHttpTest = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/skipLogin',
  },
});

// 订单微服务Axios对象
export const commodityHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-product',
  },
});

// 订单微服务Axios对象
export const orderHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-order',
  },
});

// 部署微服务Axios对象
export const deployHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslandingDeployment',
  },
});

// 升级微服务Axios对象
export const upgradeHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-upgrade',
  },
});
// 工单微服务Axios对象
export const workOrderHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-worksheet',
  },
});
// job微服务Axios对象
export const jobHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-job',
  },
});

// 运营微服务Axios对象
export const operationHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-operation',
  },
});
export const loginHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-auth',
  },
});
export const maintenanceHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-maintenance',
  },
});

export const measurementHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-measurement',
  },
});

export const logHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-log',
  },
});

// 集成微服务Axios对象
export const integratedHttp = createAxios({
  requestOptions: {
    apiUrl: globSetting.apiUrl + '/saaslanding-integrated',
  },
});
